#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime
from data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""journey_mark_item collection has
    userid:         用户id（int）
    markid:         景点评论id（int）
    mark:           景点评论（string）
    ctime:          景点评论创建时间（datetime），由客户端生成
"""

journey_mark_table_dict = {}


class JourneyMarkTables(object):
    def make_table(self, p_cityid):
        if journey_mark_table_dict.has_key(p_cityid):
            return journey_mark_table_dict[p_cityid]

        class JourneyMarkItem(object):
            def __init__(self, p_cityid):
                self.p_cityid = p_cityid

            def to_dict(self):
                res = {}
                res['userid'] = self.userid
                res['markid'] = self.markid
                res['mark'] = self.mark
                res['ctime'] = self.ctime
                return res

            def __repr__(self):
                return "%d" % (self.userid)

        metadata = MetaData()
        journey_mark_item_table = Table(
            'journey_mark_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('userid', Integer, index=True, nullable=False),
            Column('markid', Integer, index=True, nullable=False),
            Column('mark', UnicodeText, index=True, nullable=False),
            Column('ctime', DateTime, nullable=False))
        mapper(JourneyMarkItem, journey_mark_item_table)
        table = {'metadata': metadata,
                 'table': journey_mark_item_table,
                 'class': JourneyMarkItem}
        journey_mark_table_dict[p_cityid] = table
        return table


def create_journey_mark_item_table_if_not_exist(p_cityid):
    table = JourneyMarkTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


def add_journey_mark_item(p_cityid, p_item):
    table = JourneyMarkTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.userid = p_item['userid']
    item.markid = p_item['markid']
    item.mark = p_item['mark']
    item.ctime = p_item['ctime']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


'''
{'markid': 1L, 'userid': 111L, 'ctime': datetime.datetime(2015, 4, 27, 16, 19, 23), 'mark': u'\u4eca\u5929\u4e2d\u5348\u996d\u5802'}
'''


def get_journey_mark_by_userid_markid(p_cityid, p_userid, p_markid):
    try:
        session = Session()
        table = JourneyMarkTables().make_table(p_cityid)
        item = session.query(table['class']).filter_by(userid=p_userid, markid=p_markid).first()
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
        # session.remove()


def get_journey_mark_all_by_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyMarkTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by(userid=p_userid).all()
        res = {}
        for item in items:
            res[item.markid] = item.to_dict()
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
        # session.remove()


def get_markid_by_cityid_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyMarkTables().make_table(p_cityid)
        items = session.query(table['class'].userid, table['class'].markid).filter_by(userid=p_userid).all()
        res = {}
        for (userid, markid) in items:
            res['userid'] = userid
            res['markid'] = markid
            res.update(res)
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def delete_journey_mark_by_userid(p_cityid, p_userid):
    try:
        session = Session()
        table = JourneyMarkTables().make_table(p_cityid)
        item = session.query(table['class']).filter_by(userid=p_userid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    '''
    test_city = 1
    create_journey_mark_item_table_if_not_exist(test_city)
    test_item = {'userid': 1,
                 'markid': 1,
                 'mark': 'test',
                 'ctime': '2015-04-01 14:27:53' }
    add_journey_mark_item(test_city, test_item)
    print get_journey_mark_by_userid_markid( 1, 113, 1 )
    print get_markid_by_cityid_userid( 1, 1 )
    print get_journey_mark_all_by_userid( 1, 113 )
    '''
    print get_journey_mark_by_userid_markid(1, 111, 1)
